package com.chenbei.common.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.common.service.IFileUploadService;
import com.chenbei.common.domain.vo.UploadFileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;

@Service
@Slf4j
public class LocalFileUploadService implements IFileUploadService {

    @Value("${file.upload.dir}")
    private String uploadFileDir;

    @Override
    public UploadFileResult upload(MultipartFile multipartFile) {
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        String month = String.format("%02d", localDate.getMonthValue());

        String dir = year + File.separator + month;
        String filename = IdUtil.fastUUID() + "." + FileUtil.extName(multipartFile.getOriginalFilename());
        return upload(multipartFile, dir, filename);
    }

    @Override
    public UploadFileResult upload(MultipartFile multipartFile, String dir, String filename) {
        if (multipartFile.isEmpty() || multipartFile.getSize() <= 0) {
            throw new LogicHandleException("文件不能为空");
        }

        Path path = Paths.get(uploadFileDir);
        if (!path.isAbsolute()) {
            uploadFileDir = Paths.get("").toAbsolutePath().resolve(uploadFileDir).normalize().toString();
        }

        String absoluteDirPath = uploadFileDir + File.separator + dir;
        File parentFile = new File(absoluteDirPath);
        if (!parentFile.exists()) {
            if (!parentFile.mkdirs()) {
                log.error("创建目录失败，目录: {}", dir);
                throw new LogicHandleException("文件上传异常");
            }
        }

        String absoluteFilePath = absoluteDirPath + File.separator + filename;
        File file = new File(absoluteFilePath);
        try {
            Files.copy(multipartFile.getInputStream(), file.toPath());
        } catch (IOException e) {
            log.error("文件上传失败，异常信息: {}", e.getMessage());
            throw new LogicHandleException("文件上传异常");
        }

        String filePath = dir + File.separator + filename;
        String fileUrl = filePath.replaceAll("\\\\", "/");
        return new UploadFileResult(fileUrl);
    }
}
